<template>
  <div>
    <el-form @submit.native.prevent class="query-table-form" :inline="true" :model="params">
      <el-form-item>
        <el-input
          v-model="params.customer_name"
          placeholder="担保客户查询"
          clearable
          @change="getData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <c-select
          placeholder="客户类型"
          clearable
          @change="getData()"
          v-model="params.org_class"
          :options="enumCustomerType"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <select-address
          v-model="params.address_code"
          :auto-top="1"
          :bottom-level="2"
          placeholder="地址查询"
          clearable
          @change="getData()"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.bank_name"
          placeholder="银行名称查询"
          clearable
          @keyup.enter.native="getData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <select-date-cascader
          placeholder="导入时间"
          class="form-control-ml"
          v-model="queryDate"
          @select="handleDateQuery"
        ></select-date-cascader>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="getData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          icon="el-icon-download"
          :loading="exportLoading"
          @click="exportExcel('十二大产业贷')"
        >
          导出
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-delete" type="primary" @click="handleBatchDelete()">
          批量删除
        </el-button>
      </el-form-item>
    </el-form>

    <c-table
      border
      v-loading="loading"
      ref="multipleTable"
      :columns="tableColumns"
      row-key="customer_related_id"
      @selection-change="handleSelectionChange"
      :data="tableData"
    >
      <template v-slot:status="scope">
        <div class="badge" :class="`badge-${scope.row.statusStyle}`">
          {{ scope.row.statusLabel }}
        </div>
      </template>
      <template v-slot:des="scope">
        <div class="text-truncate" :title="scope.row.ex_des">{{ scope.row.ex_des }}</div>
      </template>
    </c-table>

    <div class="query-pagination">
      <div class="pl-3">
        <small class="text-muted">
          (已选择
          <span class="text-info">{{ selectLen }}</span>
          个项目)
        </small>
      </div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="tableCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <project-new-dialog
      :visible.sync="applyVisible"
      :table-id="tableId"
      :form-data="applyRow"
      @success="getData()"
    ></project-new-dialog>

    <project-view-dialog
      :visible.sync="visible"
      :batch-no="batchNo"
      :query-id="queryId"
    ></project-view-dialog>

    <attach-dialog :visible.sync="attachVisible" :project-data="attachProjectData"></attach-dialog>
  </div>
</template>
<script>
import { dataAdapter, enumCustomerType, parseCascaderDate } from '@/bank/views/limit/index'

import hndTableMixin from '@/bank/views/limit/mixins'
import SelectAddress from '@/components/select/SelectAddress'
import ProjectNewDialog from '@/bank/views/limit/ProjectNewDialog'
import ProjectViewDialog from '@/bank/views/limit/ProjectViewDialog'
import AttachDialog from '@/bank/views/limit/AttachDialog'
import SelectDateCascader from '@/components/select/SelectDateCascader'
export default {
  components: {
    SelectAddress,
    ProjectNewDialog,
    ProjectViewDialog,
    AttachDialog,
    SelectDateCascader,
  },
  mixins: [hndTableMixin],
  props: {},
  data() {
    return {
      enumCustomerType,
      params: {
        index: 1,
        size: 15,
        customer_name: '',
        'import_status.in': '2,3',
      },
      queryDate: [],
      order: {
        create_time: 'desc',
      },
      tableName: 'datum_one_county_industry',
      tableColumns: [
        {
          attrs: {
            label: '选择',
            type: 'selection',
            align: 'center',
            reserveSelection: true,
            selectable: this.onSelect,
          },
        },
        {
          attrs: { label: '借款客户', prop: 'customer_name', minWidth: '120px' },
          process: (v, row) => ({
            attrs: { class: 'project-history', attrs: { 'data-history': row.is_history } },
          }),
        },
        { attrs: { label: '客户类型', prop: 'org_class_name', align: 'center' } },
        { attrs: { label: '担保(放款)金额(万元)', prop: 'warranty_amount', align: 'center' } },
        { attrs: { label: '放款日期', prop: 'loadDate', align: 'center', minWidth: '100px' } },
        { attrs: { label: '还款日期', prop: 'loadEndDate', align: 'center', minWidth: '100px' } },
        { attrs: { label: '导入银行', prop: 'bank_name', align: 'center' } },
        { attrs: { label: '导入时间', prop: 'createTime', align: 'center', minWidth: '100px' } },
        { attrs: { label: '异常说明', prop: 'ex_des', minWidth: '120px' }, slot: 'des' },
        {
          attrs: { label: '操作', align: 'center', width: '170px' },
          operations: [
            {
              content: '修改',
              icon: 'fa fa-edit',
              event: this.handleToEdit,
              ifRender: row => this.onSelect(row),
            },
            {
              content: '删除',
              icon: 'fa fa-trash',
              attrs: { class: 'text-danger py-0 px-2' },
              event: this.handleDelete,
              ifRender: row => this.onSelect(row),
            },
            { content: '上传', icon: 'fa fa-clipboard', event: this.handleUpload },
            { content: '详情', icon: 'fa fa-search', event: this.showCreditFile },
          ],
        },
      ],

      queryId: '',
      batchNo: '',
      visible: false,

      // 编辑
      applyVisible: false,
      applyRow: {},
      tableId: '',

      attachVisible: false,
      attachProjectData: {},
      multipleSelection: [],
    }
  },
  computed: {
    selectLen() {
      return this.multipleSelection.length
    },
  },
  watch: {},
  created() {
    this.params['bank_id.eq'] = this.clientId
    this.getData()
  },
  mounted() {},
  methods: {
    onSelect(row) {
      return row.bank_id === this.clientId && +row.import_status === 2
    },
    handleBatchDelete() {
      const deleteData = []
      this.multipleSelection.forEach(item => {
        if (!item.customer_related_id) {
          return
        }
        deleteData.push(item.customer_related_id)
      })
      if (!deleteData.length) {
        return this.$message.warning('请先选择需要删除的项目')
      }
      const deleteLimit = 150
      const count = Math.ceil(deleteData.length / deleteLimit)
      const promiseAll = []

      this.$utils
        .msgbox({
          message: `确定申请删除已选的${this.multipleSelection.length}个项目?`,
          beforeClose: () => {
            for (let i = 0; i < count; i++) {
              const data = deleteData.slice(i * deleteLimit, (i + 1) * deleteLimit)
              promiseAll.push(
                this.$api.deleteData(this.$serviceName, this.tableName, data.join(','))
              )
            }
            return Promise.all(promiseAll)
          },
        })
        .then(() => {
          this.clearSelect()
          this.$message.success('删除成功')
          this.getData()
        })
        .catch(() => this.$message.error('删除失败，请重试！'))
    },
    clearSelect() {
      this.multipleSelection = []
      const $tableRef = this.$refs.multipleTable.$children[0]
      $tableRef.clearSelection()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleUpload(row = {}) {
      this.attachProjectData = row
      this.attachVisible = true
    },
    dataAdapter(item) {
      dataAdapter(item)
      item.statusLabel = '待处理'
      item.statusStyle = 'warning'
      return item
    },
    getParams() {
      return this.params
    },
    handleDateQuery(val) {
      const [start, end] = parseCascaderDate(val)
      this.params['create_time.gte'] = start
      this.params['create_time.lte'] = end
      this.getData()
    },

    handleDelete(row = {}) {
      this.$utils
        .msgbox({
          message: `确定删除客户${row.customer_name}?`,
          beforeClose: () =>
            this.$api.deleteData(this.$serviceName, this.tableName, row.customer_related_id),
        })
        .then(() => {
          this.getData()
          this.$message.success('删除成功！')
        })
        .catch(() => this.$message.error('删除失败，请重试！'))
    },
    showCreditFile(row = {}) {
      this.queryId = row.customer_related_id || ''
      this.batchNo = row.project_approval_batch_bank_id || ''
      this.visible = true
    },
    handleToEdit(row = {}) {
      this.applyRow = { ...row }
      this.tableId = this.applyRow['customer_related_id'] || ''
      this.applyVisible = true
    },
  },
}
</script>
<style lang="scss" scoped></style>
